# -*- coding: utf-8 -*-
from . import getConnection


class TodoUrl(object):

    def __init__(self, url):
        self.url = url

    def save(self):
        connection = getConnection()
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO `todo_url` (`url`) VALUE (%s)"
                cursor.execute(sql, (self.url, ))
            connection.commit()
        finally:
            connection.close()

    def existUrl(self):
        count = 0
        connection = getConnection()
        try:
            with connection.cursor() as cursor:
                sql = "SELECT count(*) as count FROM todo_url WHERE url = %s"
                cursor.execute(sql, (self.url, ))
                data = cursor.fetchone()
                count = data['count']
        finally:
            connection.close()

        return count > 0

    @classmethod
    def findUrlList(cls):
        data = None
        connection = getConnection()
        try:
            with connection.cursor() as cursor:
                sql = "SELECT id, url FROM todo_url"
                cursor.execute(sql)
                data = cursor.fetchall()
        finally:
            connection.close()

        return data

    @classmethod
    def removeUrl(cls, url_id):
        connection = getConnection()
        try:
            with connection.cursor() as cursor:
                sql = "DELETE FROM todo_url WHERE id = %s"
                cursor.execute(sql, (url_id, ))
            connection.commit()
        finally:
            connection.close()
